import * as vscode from 'vscode';
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { parse } from 'yaml';

export interface ProjectTokenInfo {
    projectId: string;
}

export const getProjectToken = (): ProjectTokenInfo | null => {
    const folders = vscode.workspace.workspaceFolders;
    if (folders == undefined || folders.length == 0) {
        vscode.window.showErrorMessage("没有打开项目");
        return null;
    }

    const ymlPath = `${folders[0].uri.fsPath}/.linksaas.yml`
    let ymlData = "";
    try {
        ymlData = readFileSync(ymlPath).toString();
    } catch (e) {
        console.log(e);
        vscode.window.showErrorMessage(`不存在配置文件${ymlPath}`);
        return null;
    }
    try {
        const obj = parse(ymlData);
        if ("projectId" in obj) {
            return {
                projectId: obj["projectId"] as string,
            }
        } else if ("project_id" in obj) {
            return {
                projectId: obj["project_id"] as string,
            }
        } else {
            return null;
        }
    } catch (e) {
        console.log(e);
        vscode.window.showErrorMessage(`解析配置文件${ymlPath}出错`);
        return null;
    }
};

export const initProjectTokenCfg = () => {
    const folders = vscode.workspace.workspaceFolders;
    if (folders == undefined || folders.length == 0) {
        vscode.window.showErrorMessage("没有打开项目");
        return;
    }
    const ymlPath = `${folders[0].uri.fsPath}/.linksaas.yml`;
    if (existsSync(ymlPath)) {
        vscode.window.showWarningMessage("配置文件已经存在");
        vscode.commands.executeCommand('vscode.open', vscode.Uri.joinPath(folders[0].uri, ".linksaas.yml"));
        return;
    }
    try {
        writeFileSync(ymlPath, "projectId: your_project_id");
        vscode.commands.executeCommand('vscode.open', vscode.Uri.joinPath(folders[0].uri, ".linksaas.yml"));
    } catch (e) {
        console.log(e);
        return;
    }
}